package com.szsky.sky.demo;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.util.Base64;

public class DESCBC {

    private static final String CHARSET = "UTF-8";

    public static void main(String[] args) {
        try {
            String originalData = "Hello, DES Encryption!";
//            # 加密用的key  浪潮信息是:ieisystem_hr，浪潮集团是:inspur_hr
            String key = "inspur_hr";

            System.out.println("原始数据: " + originalData);
            System.out.println("密钥: " + key);

            String encryptedData = encrypt(originalData, key);
            System.out.println("加密后: " + encryptedData);

            String decryptedData = decrypt(encryptedData, key);
            System.out.println("解密后: " + decryptedData);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String encrypt(String data, String key) throws Exception {
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes(CHARSET));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

        // 使用CBC模式
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

        // 创建固定的IV（初始化向量）
        byte[] iv = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07};
        IvParameterSpec ivSpec = new IvParameterSpec(iv);

        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes(CHARSET));

        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decrypt(String encryptedData, String key) throws Exception {
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData);

        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes(CHARSET));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

        // 使用相同的IV
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        byte[] iv = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07};
        IvParameterSpec ivSpec = new IvParameterSpec(iv);

        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

        return new String(decryptedBytes, CHARSET);
    }
}